package cn.npe.scanbean;

import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.util.StringUtils;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;

/**
 * 需求：JFNIA框架中 转移到spring中 需要将FNIAL其中大量的类添加到spring的容器中 为了避免大量的手工添加@Compent类似的注解
 * 需要这样实现
 * 第一种方式直接事项ImportBeanDefinitionRegistrar
 */
public class BeanScannerRegistrar implements ImportBeanDefinitionRegistrar {
    /**
     *
     * @param importingClassMetadata 将该类import进来的类的元数据信息
     * @param registry
     * @param importBeanNameGenerator
     */
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, BeanNameGenerator importBeanNameGenerator) {
        boolean acceptAllBeans=true;
        AnnotationAttributes attributes=AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(BeanScanner.class.getName()));
        BeanPackageScanner scanner=new BeanPackageScanner(registry);
        Class<? extends Annotation> annotationClass=attributes.getClass("annotationClass");

        if (!Annotation.class.equals(annotationClass)){
            acceptAllBeans=false;
            scanner.addIncludeFilter(new AnnotationTypeFilter(annotationClass));
        }


        List<String> basePackages = new ArrayList<String>();
        for (String pkg : attributes.getStringArray("value")) {
            if (StringUtils.hasText(pkg)) {
                basePackages.add(pkg);
            }
        }
        for (String pkg : attributes.getStringArray("basePackages")) {
            if (StringUtils.hasText(pkg)) {
                basePackages.add(pkg);
            }
        }

        if (acceptAllBeans){
            //重写match方法
            scanner.addIncludeFilter((metadataReader,metadataReaderFactory)->true);
        }

        scanner.doScan(StringUtils.toStringArray(basePackages));
    }
}
